<template>
  <div class="exam-container">
    <el-card class="exam-card">
      <!-- 考试头部信息 -->
      <div class="exam-header">
        <h2>{{ examInfo.title }}</h2>
        <div class="exam-meta">
          <span>总分: {{ examInfo.totalScore }}分</span>
          <span>时间: {{ examInfo.duration }}分钟</span>
          <el-progress 
            :percentage="progress" 
            :format="formatProgress" 
            class="time-progress"
          />
          <span>剩余时间: {{ remainingTime }}</span>
        </div>
      </div>

      <!-- 考生信息 -->
      <el-card shadow="never" class="student-info">
        <el-descriptions title="考生信息" :column="2" border>
          <el-descriptions-item label="姓名">{{ studentInfo.name }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ studentInfo.id }}</el-descriptions-item>
          <el-descriptions-item label="班级">{{ studentInfo.class }}</el-descriptions-item>
          <el-descriptions-item label="考试科目">{{ examInfo.subject }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 题目区域 -->
      <div class="question-area">
        <div v-for="(question, index) in questions" :key="question.id" class="question-item">
          <div class="question-title">
            <span class="question-number">第{{ index + 1 }}题 ({{ question.score }}分):</span>
            <span>{{ question.title }}</span>
          </div>
          
          <!-- 单选题 -->
          <div v-if="question.type === 'single-choice'" class="question-options">
            <el-radio-group v-model="answers[question.id]">
              <el-radio 
                v-for="option in question.options" 
                :key="option.key" 
                :label="option.key"
                class="option-item"
              >
                {{ option.key }}. {{ option.text }}
              </el-radio>
            </el-radio-group>
          </div>
          
          <!-- 多选题 -->
          <div v-if="question.type === 'multiple-choice'" class="question-options">
            <el-checkbox-group v-model="answers[question.id]">
              <el-checkbox 
                v-for="option in question.options" 
                :key="option.key" 
                :label="option.key"
                class="option-item"
              >
                {{ option.key }}. {{ option.text }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          
          <!-- 填空题 -->
          <div v-if="question.type === 'fill-blank'" class="question-options">
            <el-input
              v-model="answers[question.id]"
              :placeholder="'请输入答案'"
              clearable
            />
          </div>
          
          <!-- 简答题 -->
          <div v-if="question.type === 'short-answer'" class="question-options">
            <el-input
              v-model="answers[question.id]"
              type="textarea"
              :rows="4"
              :placeholder="'请输入答案'"
            />
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="submitExam">提交试卷</el-button>
        <el-button @click="saveTemp">暂存答案</el-button>
      </div>
    </el-card>

    <!-- 提交确认对话框 -->
    <el-dialog
      v-model="confirmDialogVisible"
      title="确认提交"
      width="30%"
    >
      <span>确定要提交试卷吗？提交后将无法修改答案。</span>
      <template #footer>
        <el-button @click="confirmDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit">确定提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'

import ExamAPI from '@/api/exam'

// 考试信息
const examInfo = reactive({
  title: '2023年期末考试',
  subject: 'Vue.js 高级开发',
  totalScore: 100,
  duration: 120,
  startTime: new Date()
})
const route = useRoute()

// 学生信息
const studentInfo = reactive({
  name: '张三',
  id: '20230001',
  class: '计算机科学与技术1班'
})

// 题目数据
const questions = reactive([
  {
    id: 1,
    type: 'single-choice',
    title: 'Vue 3 中用于组合式API的入口函数是什么？',
    score: 5,
    options: [
      { key: 'A', text: 'setup' },
      { key: 'B', text: 'create' },
      { key: 'C', text: 'init' },
      { key: 'D', text: 'main' }
    ]
  },
  {
    id: 2,
    type: 'multiple-choice',
    title: '下列哪些是 Vue 3 的新特性？',
    score: 10,
    options: [
      { key: 'A', text: 'Composition API' },
      { key: 'B', text: 'Teleport' },
      { key: 'C', text: 'Fragments' },
      { key: 'D', text: 'Options API' }
    ]
  },
  {
    id: 3,
    type: 'fill-blank',
    title: 'Vue 3 中使用_____指令进行条件渲染。',
    score: 5
  },
  {
    id: 4,
    type: 'short-answer',
    title: '请简述 Vue 3 的 Composition API 相比于 Options API 的优势。',
    score: 20
  }
])

// 答案存储
const answers = ref({})

// 考试时间处理
const examEndTime = computed(() => {
  const endTime = new Date(examInfo.startTime)
  endTime.setMinutes(endTime.getMinutes() + examInfo.duration)
  return endTime
})

const remainingTime = ref('')
const progress = ref(0)
let timer = null

const updateTime = () => {
  const now = new Date()
  const diff = examEndTime.value - now
  
  if (diff <= 0) {
    remainingTime.value = '考试已结束'
    progress.value = 100
    clearInterval(timer)
    autoSubmitExam()
    return
  }
  
  const minutes = Math.floor(diff / (1000 * 60))
  const seconds = Math.floor((diff % (1000 * 60)) / 1000)
  remainingTime.value = `${minutes}分${seconds}秒`
  
  const totalDuration = examInfo.duration * 60 * 1000
  progress.value = ((totalDuration - diff) / totalDuration) * 100
}

const formatProgress = () => {
  return `考试进度: ${progress.value.toFixed(1)}%`
}

// 自动提交考试
const autoSubmitExam = () => {
  ElMessage.warning('考试时间已到，系统将自动提交您的试卷')
  submitExam()
}

// 提交考试
const confirmDialogVisible = ref(false)

const submitExam = () => {
  // 检查是否有未答题目
  const unanswered = questions.filter(q => !answers.value[q.id])
  if (unanswered.length > 0) {
    ElMessageBox.confirm(
      `您还有 ${unanswered.length} 题未作答，确定要提交吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      confirmDialogVisible.value = true
    })
  } else {
    confirmDialogVisible.value = true
  }
}

const confirmSubmit = () => {
  // 这里应该是提交到后端API的逻辑
  console.log('提交的答案:', answers.value)
  ElMessage.success('试卷提交成功！')
  confirmDialogVisible.value = false
  // 跳转到结果页面或其他操作
}

// 暂存答案
const saveTemp = () => {
  // 这里应该是保存到本地或后端的逻辑
  localStorage.setItem('exam_answers', JSON.stringify(answers.value))
  ElMessage.success('答案已暂存')
}


function getExamInfo(){
	//获取url参数的paperid
	const queryParam = route.query
	const id = route.query.id
	
	//使用paperid查询试卷信息
	console.log(id);
	
	ExamAPI.getExamInfoById(id).then((data)=>{
		console.log(data)
	})
	
	
}

// 初始化
onMounted(() => {
  // 加载暂存的答案
  const savedAnswers = localStorage.getItem('exam_answers')
  if (savedAnswers) {
    answers.value = JSON.parse(savedAnswers)
    ElMessage.info('检测到暂存答案，已自动加载')
  }
  
  // 启动计时器
  timer = setInterval(updateTime, 1000)
  updateTime()
  getExamInfo()
})

onBeforeUnmount(() => {
  clearInterval(timer)
})
</script>

<style scoped>
.exam-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.exam-card {
  margin-bottom: 20px;
}

.exam-header {
  margin-bottom: 20px;
  text-align: center;
}

.exam-header h2 {
  margin-bottom: 10px;
}

.exam-meta {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 15px;
}

.time-progress {
  width: 200px;
}

.student-info {
  margin-bottom: 20px;
}

.question-area {
  margin-top: 30px;
}

.question-item {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.question-title {
  margin-bottom: 15px;
  font-weight: bold;
}

.question-number {
  margin-right: 10px;
  color: #409eff;
}

.question-options {
  margin-left: 20px;
}

.option-item {
  display: block;
  margin: 8px 0;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
}
</style>